﻿using SpotsHub.Tools.MassUploader.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SpotsHub.Tools.MassUploader
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            string root = ConfigurationManager.AppSettings["RootPath"];
            if (Directory.Exists(root))
            {
                linkLabelTemplatePath.Text = root;
            }
            enableButtons(false);
            timerLog.Start();
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            if (!DataAdapter.Instance.Connected)
            {
                try
                {
                    DataAdapter.Instance.ConnectToDatabase();
                    buttonConnect.Enabled = false;
                    enableButtons(true);
                }
                catch (Exception ex)
                {
                    Logger.Inst.Add(LogType.Error, "Cannot connect to the database: {0}", ex);
                }
            }

            updateDatabaseStatus();
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                e.Cancel = true;
                return;
            }
            if (Directory.Exists(linkLabelTemplatePath.Text))
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                AppSettingsSection app = config.AppSettings;
                app.Settings["RootPath"].Value = linkLabelTemplatePath.Text;
                config.Save(ConfigurationSaveMode.Modified);
            }

            
            DataAdapter.Instance.Disconnect();
        }

        private void enableButtons(bool enable)
        {
            button2.Enabled = enable;
            button3.Enabled = enable;
            buttonProducts.Enabled = enable;
        }

        private void updateDatabaseStatus()
        {
            if (DataAdapter.Instance.Connected)
            {
                labelDatabase.Text = "The database has been connected successfully!";
            }
            else
            {
                labelDatabase.Text = "Not connected.";
            }
        }

        private void buttonProducts_Click(object sender, EventArgs e)
        {
            new Forms.DatabaseProducts().ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //var t = PermissionController.GetExternalIp();
            //MessageBox.Show(t);
            
            //var t = new ProductAttribute();
            //t.ProductAttributes = DataAdapter.Instance.GetProductAttributeNames();
            //t.ShowDialog();

            var key = FileEncryptor.GenerateKey();

            FileStream fsInput = new FileStream("Settings.txt",
                FileMode.Open,
                FileAccess.Read);

            FileStream fsEncrypted = new FileStream("Settings.Enc",
               FileMode.Create,
               FileAccess.Write);

            fsEncrypted.Write(key, 0, key.Length);

            FileEncryptor.EncryptFile(fsInput, fsEncrypted, key);

            fsInput.Close();
            fsEncrypted.Close();

            fsEncrypted = new FileStream("Settings.Enc",
               FileMode.Open,
               FileAccess.Read);

            fsEncrypted.Read(key, 0, 8);

            FileStream newFile = new FileStream("NewSettings.Txt",
               FileMode.Create,
               FileAccess.Write);

            FileEncryptor.DecryptFile(fsEncrypted, newFile, key);
            fsEncrypted.Close();
            newFile.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // Import
            if (!DataAdapter.Instance.Connected)
            {
                MessageBox.Show("Database is not connected.");
                return;
            }

            string dir = linkLabelTemplatePath.Text;

            var dlg = new FolderBrowserDialog();
            if (Directory.Exists(dir))
            {
                dlg.SelectedPath = dir;
            }
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                linkLabelTemplatePath.Text = dlg.SelectedPath;
                dir = dlg.SelectedPath;
            }
            else
            {
                return;
            }

            if (System.IO.Directory.Exists(dir))
            {
                var pg = ProductGenerator.CreateProductsFromTemplate(dir);
                pg.Import();

                if (pg.ProductsInformation.Rows.Count > 0)
                {
                    var dlgCfm = new ProductsReview();
                    dlgCfm.Result = pg;
                    if (dlgCfm.ShowDialog() == DialogResult.OK)
                    {
                        if (DataAdapter.Instance.Connected && pg != null)
                        {
                            enableButtons(false);
                            initProgressBar(pg.ProductsInformation.Rows.Count);
                            if (backgroundWorker1.IsBusy != true)
                            {
                                backgroundWorker1.RunWorkerAsync(new DataAdapter.ImportParams() { progress = backgroundWorker1, pg = pg });
                            }
                        }
                    }
                }
            }
            else
            {
                Logger.Inst.Add("The template folder ({0}) doesn't exist.", dir);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //Create template

            if (!DataAdapter.Instance.Connected)
            {
                MessageBox.Show("Database is not connected.");
                return;
            }

            var dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                var chooseDlg = new ChooseStore();
                if (chooseDlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    MessageBox.Show("Must choose a store as the default store.");
                    return;
                }

                ProductGenerator.CreateEmptyTemplate(dlg.SelectedPath, chooseDlg.SelectedStoreId);
                linkLabelTemplatePath.Text = dlg.SelectedPath;
            }
        }

        private void linkLabelTemplatePath_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            if (System.IO.Directory.Exists(linkLabelTemplatePath.Text))
            {
                string args = string.Format("/Select, {0}", linkLabelTemplatePath.Text);

                var pfi = new System.Diagnostics.ProcessStartInfo("Explorer.exe", args);
                System.Diagnostics.Process.Start(pfi);
            }
        }

        private void timerLog_Tick(object sender, EventArgs e)
        {
            if (Logger.Inst.Dirty)
            {
                Logger.Inst.DumpToRichTextBox(richLog);
            }
        }

        private void initProgressBar(int count)
        {
            progressBar1.Minimum = 0;
            progressBar1.Maximum = count;
            progressBar1.Step = 1;
            progressBar1.Value = 0;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            DataAdapter.Instance.ImportProducts(e.Argument);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.PerformStep();
            progressBar1.Update();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            enableButtons(true);
            if (e.Cancelled == true)
            {
                Logger.Inst.Add(LogType.Error, "Cancellation is not supported.");
                return;
            }

            if (e.Error != null)
            {
                Logger.Inst.Add(LogType.Error, "Fault error: {0}", e.Error);
            }
            else
            {
                Logger.Inst.Add("Importing all products completely.");
            }
        }
    }
}
